﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml.Controls;
using SplitViewOptions.Model;

namespace SplitViewOptions.ViewModel
{
    public class HistoryModel : NotifyProperty
    {
        public HistoryModel()
        {
            Read();
        }

        public async void Read()
        {
            var history = HistoryWebModel.HistoryWeb;
            //最后时间
                DateTime min = history.HistoryTime.First().Time;
            if (history.HistoryTime.Count == 0)
            {
                _time = DateTime.Now;
            }
            else
            {
                foreach (var temp in history.HistoryTime)
                {
                    if (min > temp.Time)
                    {
                        min = temp.Time;
                    }
                }
                _time = min;
            }

            int length = history.HistoryTime.Count + 10;

            string str = "history";
            min=DateTime.Now;
            try
            {
                StorageFolder folder = await
                    ApplicationData.Current.LocalFolder.GetFolderAsync(str);
                var file = await folder.GetFilesAsync();
                foreach (var temp in file)
                {
                    var time = (await temp.GetBasicPropertiesAsync()).ItemDate.DateTime;
                    if (min > time)
                    {
                        min = time;
                    }
                }
                min = min.AddDays(-1);
            }
            catch
            {

            }
            while (history.HistoryTime.Count<length  && _time>min)
            {
               _time= _time.AddDays(-1);
                await history.Read(_time);
            }
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () =>
                {
                    HistoryTime.Clear();
                    foreach (var temp in history.HistoryTime)
                    {
                        HistoryTime.Add(temp);
                    }
                });

        }

        private ObservableCollection<History> _history;

        public ObservableCollection<History> HistoryWeb
        {
            set
            {
                _history = value;
                OnPropertyChanged();
            }
            get
            {
                return _history;
            }
        }

        public ObservableCollection<TimeHistory> HistoryTime
        {
            set;
            get;
        }=new ObservableCollection<TimeHistory>();

        private DateTime _time;

        public void HistoryTimeRead(object sender, ItemClickEventArgs e)
        {
            
        }
    }
}
